import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;


public class Splitter implements Runnable {
	
			//ATTRIBUTI DI CLASSE
			private File file;
			private int L;
			private Cell[] ar;
			private InetAddress IPDest;
			private int portDest;
			InetAddress IPSo;
			int portSo;
		
			//METODO COSTRUTTORE
			public Splitter(File fil, int Lu, Cell[] arr, InetAddress IPDestination, int portDestination, InetAddress IPSource, int portSource) {
				
				 this.file = fil;
				 this.L = Lu;
				 this.ar = arr;
				 this.IPDest = IPDestination;
				 this.portDest = portDestination;
				 this.IPSo = IPSource;
				 this.portSo =portSource;
			     }
				
			
			public static long dimFile(File f){ 									 //Restituisce la dim file 
	
				return f.length();
				}
			
			public void born(Cell[] arr, InetAddress IPDest, int portDest, InetAddress IPSo, int portSo, int l, byte[] buf){ //Genera le celle
				
				Packet p;
				int count = 0;
				boolean fineFile = false;
                for (int j=0;j<arr.length;j++){
                	byte[] data = new byte[l-16];
                	for (int k=count;k<count+l-16;k++){
                		if(k < buf.length)
                			data[k - j*(l-16)]= buf[k];
                		else
                		{
                			fineFile = true;
                   			break;        			
                		}
         
                	    }
                	count = count + l - 16;
               	    p = new Packet(IPDest, portDest, IPSo, portSo, j, data);
               	    arr[j] = new Cell(p,0);
               	    if (fineFile)
               	    	break;
                    }
                
                System.out.println("Array di celle creato");
			}
			
			public void run(){
			
				try{
						long dimensioneFile=dimFile(this.file);
						FileInputStream fis=new FileInputStream (this.file);
						System.out.println("Ho aperto il file");
						if (dimensioneFile < Integer.MIN_VALUE || dimensioneFile > Integer.MAX_VALUE) {
							System.err.println(dimensioneFile + "File oversize.");
							System.exit(1);
						}
                
						int i=(int)dimensioneFile;                                       //i e' la dimensione del file totale
						byte[] bufFile=new byte[i];										 //metto il file in memoria      
						for(int j=0;j<i;j++){                                            //metto tutto il file in un buffer di dim uguale a quella del file
							bufFile[j]=(byte)fis.read();
                    	}
						fis.close();
						born(this.ar, this.IPDest, this.portDest, this.IPSo, this.portSo, this.L, bufFile); 
						System.out.println("Chiudo il file in lettura");
						
				}catch ( IOException e){
						System.out.println("Errore lettura/chiusura file");
						System.exit(1);
				}
               
			}
			
	}
